<template>
  <base-breadcrumb :title="titleName" :breadcrumb="!isAudit">
    <div class="about-master-container">
      <BForms ref="form">
        <a-card v-loading="loading">
          <title-name title="基本信息" />
          <BForm
            :config="formConfig"
            :form="form"
            :rule="formRules"
            @selectOrg="selectOrg"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="项目部评审人员" />
          <BForm
            :config="form2Config"
            :form="form"
            :rule="formRules"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="分公司商务法务部评审人员" />
          <BForm
            :config="form3Config"
            :form="form"
            :rule="formRules"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="公司商务、法务部评审人员" />
          <BForm
            :config="form4Config"
            :form="form"
            :rule="formRules"
          />
        </a-card>
        <a-card v-loading="loading">
          <title-name title="附件" />
          <BTableUpload
            v-model="form.file"
            :disabled="disabled"
            business-code="BM15"
          />
        </a-card>
      </BForms>
      <div v-if="!isConsultation" class="tar page-btn-right-top">
        <BasePrintButton
          v-if="form.id && disabled && !this.$route.query.businessId"
          :before-print-fn="beforePrintFn"
          style="display: inline-block;margin-right: 10px;"
        />
        <template v-if="!disabled">
          <a-button type="primary" :loading="saveLoading" :disabled="submitLoading" class="mr10p"
                    @click="save('DRAFT',false)"
          >
            保存草稿
          </a-button>
          <a-button type="primary" :loading="submitLoading" :disabled="saveLoading" class="mr10p" @click="submit()">
            提交
          </a-button>
        </template>
        <a-button v-checkVisibleInDetail @click="$close">关闭</a-button>
      </div>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import subcontract from '@/api/legal/branchContract/subcontract'
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import SelectUndertaking from '@/components/Select/SelectUndertaking'
import BTableUpload from '@/components/BComponents/BTableUpload'
import benefitAnalysisApi from '@/api/material/benefitAnalysis/defalut'
import moment from 'moment'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'


export default {
  name: 'a' + Date.now(),
  components: {
    BTableUpload
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    /* eslint-disable */
    formConfig() {
      return [
        {
          row: true,
          children: [
            { type: 'input', value: 'contractName', label: '合同名称', colSpan: 24, attrs: { disabled: this.disabled } },
            { type: 'input', value: 'code', label: '合同编号', attrs: { disabled: this.disabled } },
            { type: 'input', value: 'firstParty', label: '甲方', attrs: { disabled: this.disabled } },
            {
              label: '所属单位',
              type: 'orgTree',
              keyName: 'projectId',
              rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
              span: 8,
              isAutoSelectFirst:true,
              isNeedAuth:true,
              checkStrictly: true,
              disabled: this.disabled,
              statusSet:[1,2,3,4,5,6],
              isQueryProjecDetail: false
            },
            // {
            //   type: SelectSubCompany,
            //   value: 'branchComId',
            //   label: '所属分公司',
            //   attrs: {
            //     autoSelected: this.form.id === null
            //   },
            //   on: {
            //     selectChange: (e) => {
            //      this.form.branchComName = e.orgName
            //     this.$set(this.form, 'subcontractorScc', undefined)
            //      this.$set(this.form, 'projectId', undefined)
            //      this.$set(this.form, 'projectName', undefined)
            //    }
            //   },
            //   show: !this.disabled
            // },
            // {
            //   type: SelectProject,
            //   value: 'projectId',
            //   label: '项目名称',
            //   attrs: {
            //     isUseChangeEvent:true,
            //     isEdit: this.form.id !== null,
            //     form: this.form,
            //     keyValue: 'branchComId'
            //   },
            //   on: {
            //     selectChange: e => {
            //       if (e) {
            //         this.form.projectName = e.name
            //       }
            //     }
            //   },
            //   show: !this.disabled
            // },
            // {
            //   type: 'input',
            //   value: 'branchComName',
            //   label: '所属分公司',
            //   attrs: { disabled: this.disabled },
            //   show: this.disabled
            // },
            // {
            //   type: 'input',
            //   value: 'projectName',
            //   label: '项目名称',
            //   attrs: { disabled: this.disabled },
            //   show: this.disabled
            // },

            { type: 'input', value: 'subSupplyCompany', hidden:this.$route.query.detail == 2,label: '分包商', attrs: { disabled: this.disabled }, show: this.disabled },
            {
               type: BSelect,value: 'subcontractorScc', label: '分包商',
               hidden:this.$route.query.detail == 1,
              attrs: {
                disabled: this.disabled,
                 list: this.subcontractorData,
                 isSearch:true
              },
              on: {
                change: (e) => {
                  let findName = this.subcontractorData.find((item)=>item.id === e);
                  this.form.subcontractorName = findName?.name;
                },
                change2:(e)=>{
                    if(!e){
                      this.subcontractorData = [];
                      this.pageNo = 1;
                      this.getSubContractorAllFn();
                  }
                },
                search:(e)=>{
                  if(e){
                      this.subcontractorData = [];
                      this.pageNo = 1;
                      this.getSubContractorAllFn(e);
                  }

                },
                popupScroll:(e)=>{
                 const { target } = e
                var total = target.scrollTop + target.offsetHeight;
                var scrollHeight = target.scrollHeight

                // this.pageNo是当前页 this.totalPage是总页数
                if (total >= scrollHeight - 1 && total < scrollHeight + 1) {
                  this.pageNo = this.pageNo + 1
                  this.getSubContractorAllFn();
                }
               }
            },
              show: !this.disabled
            },
           {
              type: BSelect, value: 'localContractType', label: '合同种类', attrs: {
                disabled: true, list: [
                  { id: 0, name: '主合同' },
                  { id: 1, name: '补充协议' }
                ]
              }
            },
            {
              type: BSelect, value: 'contractTypeId', label: '分包方式',
              attrs: {
                disabled: this.disabled,
                request: () => subcontract.typesLabel({ query: { type: 21 } })
              }
            },
            {
              type: 'number', value: 'contractExTaxAmount', label: '合同额（不含税）（元）',
              attrs: { disabled: this.disabled, precision: 2, min: 0 },
              on: {
                change: (e) => {
                  if (this.form.contractRate) {
                    this.form.contractInTaxAmount = e + this.form.contractRate
                  }
                }
              }
            },
            {
              type: 'number', value: 'contractRate', label: '税金（元）',
              attrs: { disabled: this.disabled, precision: 2, min: 0 },
              on: {
                change: (e) => {
                  if (this.form.contractExTaxAmount) {
                    this.form.contractInTaxAmount = e + this.form.contractExTaxAmount
                  }
                }
              }
            },
            {
              type: 'number', value: 'contractInTaxAmount', label: '合同额（含税）（元）',
              attrs: { disabled: true, precision: 2, min: 0 }
            },
            {
              type: 'date-picker', value: 'startDate', label: '合同约定开工时间', attrs: {
                disabled: this.disabled,
                valueFormat: 'YYYY-MM-DD HH:mm:SS'
              }
            },
            {
              type: 'date-picker',
              value: 'endDate',
              label: '合同约定竣工时间',
              attrs: {
                disabled: this.disabled,
                valueFormat: 'YYYY-MM-DD HH:mm:SS',
                disabledDate: this.disabledDate
              }
            },
            {
              type: BSelect, value: 'payTypeId', label: '付款方式',
              attrs: {
                disabled: this.disabled,
                request: () => subcontract.typesLabel({ query: { type: 26 } })
              }
            },
            {
              type: 'number', value: 'progressPro', label: '进度付款比例（%）', attrs: {
                disabled: this.disabled,
                min: 0,
                max: 100,
                precision: 2
              }
            },
            {
              type: 'number', value: 'finishedPro', label: '完工付款比例（%）', attrs: {
                disabled: this.disabled,
                min: 0,
                max: 100,
                precision: 2
              }
            },
            {
              type: 'number', value: 'settlementPro', label: '结算完毕付款比例（%）', attrs: {
                disabled: this.disabled,
                min: 0,
                max: 100,
                precision: 2
              }
            },
            {
              type: BSelect, value: 'textTypeId', label: '采用文本',
              attrs: {
                disabled: this.disabled,
                request: () => subcontract.typesLabel({ query: { type: 22 } })
              }
            },
            {
              type: 'textarea', value: 'contentSurvey', label: '分包工程/采购、租赁范围内容概况', colSpan: 24,
              noFixed: true,
              attrs: { maxLength: 1000, disabled: this.disabled }
            },
            {
              type: 'textarea', value: 'actualSituation', label: '分供方合同谈判修改及落实情况', colSpan: 24,
              noFixed: true,
              attrs: { maxLength: 1000, disabled: this.disabled }
            },
            {
              type: 'radio', value: 'processTrend', label: '流程走向', colSpan: 24, noFixed: true,
              show: this.showProcessTrend(),
              attrs: {
                disabled: this.disabled,
                data: [
                  { id: '1', name: '项目发起＞500万分包合同、项目发起≤500万分包合同（非实体性成本支出）' },
                  { id: '2', name: '甲指分包合同、分包备案合同、项目发起≤500万分包合同（实体性成本支出）' }
                ]
              }
            },
            { type: 'input', value: 'creatorName', label: '创建人', attrs: { disabled: true } },
            { type: 'input', value: 'createTime2', label: '创建时间', attrs: { disabled: true } }
          ]
        }
      ]
    },
    form2Config() {
      return [
        {
          row: true,
          children: [
            { type: SelectUndertaking, value: 'a13', label: '工程部', show: !this.disabled },
            { type: SelectUndertaking, value: 'a14', label: '技术部', show: !this.disabled },
            { type: SelectUndertaking, value: 'a15', label: '财务资金部', show: !this.disabled },
            { type: SelectUndertaking, value: 'a16', label: '安全环境部', show: !this.disabled },
            { type: SelectUndertaking, value: 'a17', label: '物资管理部', show: !this.disabled },
            {
              type: 'input',
              value: 'a13.label',
              label: '工程部',
              attrs: { disabled: this.disabled },
              show: this.disabled
            },
            {
              type: 'input',
              value: 'a14.label',
              label: '技术部',
              attrs: { disabled: this.disabled },
              show: this.disabled
            },
            {
              type: 'input',
              value: 'a15.label',
              label: '财务资金部',
              attrs: { disabled: this.disabled },
              show: this.disabled
            },
            {
              type: 'input',
              value: 'a16.label',
              label: '安全环境部',
              attrs: { disabled: this.disabled },
              show: this.disabled
            },
            {
              type: 'input',
              value: 'a17.label',
              label: '物资管理部',
              attrs: { disabled: this.disabled },
              show: this.disabled
            }
          ]
        }
      ]
    },
    form3Config() {
      return [
        {
          row: true,
          children: [
            {
              type: ASelectOrgPeople, value: 'bcBmywjl', label: '商务法务部商务业务经理/业务主办', show: !this.disabled, attrs: {
                requestParams: { postCodes: ['BCBMYWJL', 'BCBMYWZB', 'BCLCMYWZB', 'BCLCMYWJL'] },
                form: this.form,
                keyValue: 'branchComId',
                needRootOrgId: true,
                init: false
              },
              on: {
                onSelectChange: e => {
                  this.form.bcBmywjlName = e.name
                }
              }
            },
            {
              type: 'input',
              value: 'bcBmywjlName',
              label: '商务法务部商务业务经理/业务主办',
              attrs: { disabled: this.disabled },
              show: this.disabled
            }
          ]
        }
      ]
    },
    form4Config() {
      return [
        {
          row: true,
          children: [
            {
              type: ASelectOrgPeople, value: 'coBmywzb', label: '商务管理部业务经理/业务主办', show: !this.disabled, attrs: {
                requestParams: { postCodes: ['COBMYWJL', 'COBMYWZB'] },
                orgId: '53085e2c9f1f4685801ef31994f57c49',
                needRootOrgId: true
              },
              on: {
                onSelectChange: e => {
                  this.form.coBmywzbName = e.name
                }
              }
            },
            {
              type: ASelectOrgPeople, value: 'coLcmywzb', label: '合约法务部业务经理/业务主办', show: !this.disabled, attrs: {
                requestParams: { postCodes: ['COLCMYWJL', 'COLCMYWZB'] },
                orgId: '53085e2c9f1f4685801ef31994f57c49',
                needRootOrgId: true
              },
              on: {
                onSelectChange: e => {
                  this.form.coLcmywzbName = e.name
                }
              }
            },
            {
              type: 'input',
              value: 'coBmywzbName',
              label: '商务法务部商务业务经理/业务主办',
              attrs: { disabled: this.disabled },
              show: this.disabled
            },
            {
              type: 'input',
              value: 'coLcmywzbName',
              label: '合约法务部业务经理/业务主办',
              attrs: { disabled: this.disabled },
              show: this.disabled
            }
          ]
        }
      ]
    },
    loading() {
      return this.submitLoading || this.saveLoading
    }
  },
  watch: {
    'form.id'() {
      this.showProcessTrend()
    },
    'form.branchComId':{
      handler(newVal, oldVal) {
        this.subcontractorData = [];
        this.pageNo = 1;
         newVal &&	this.getSubContractorAllFn();
			},
			deep:true, // 深度监听

    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.disabled = true
        }
      }
    }
  },
  data() {
    return {
      beforePrintFn: async () => {
        let res = await subcontract.print({}, { id: this.form.id })
        return res.data.content
      },
      submitLoading: false,
      saveLoading: false,
      disabled: this.$route.query.detail == 1,
      isContract: this.$route.query.isContract == 1,
      titleName: '分包合同',
      form: {
        id: null,
        projectId:'',
        branchComId:'',
        file: [],
        localContractType: 0,
        // processTrend: '3',
        startDate: '',
        creatorName: this.$userInfo().name,
        createTime2: this.$dateFormat(Date.now(), 'D')
      },
      formRules: {
        code: { required: true, message: '请填写合同编号', trigger: 'blur' },
        progressPro: { required: true, message: '请填写进度付款比例（%）', trigger: 'blur' },
        finishedPro: { required: true, message: '请填写完工付款比例（%）', trigger: 'blur' },
        settlementPro: { required: true, message: '请填写结算完毕付款比例（%）', trigger: 'blur' },
        startDate: { required: true, message: '请选择合同约定开工时间', trigger: 'change' },
        projectId: { required: true, message: '请选择项目名称', trigger: 'change' },
        branchComId: { required: true, message: '请选择所属分公司', trigger: 'change' },
        payTypeId: { required: true, message: '请选择付款方式', trigger: 'change' },
        endDate: { required: true, message: '请选择合同约定竣工时间', trigger: 'change' },
        contractExTaxAmount: { required: true, message: '请填写合同额（不含税）（元）', trigger: 'blur' },
        contractRate: { required: true, message: '请填写税金（元）', trigger: 'blur' },
        firstParty: { required: true, message: '请填写甲方', trigger: 'blur' },
        contractName: { required: true, message: '请填写合同名称', trigger: 'blur' },
        subcontractorScc: { required: true, message: '请填写分包商', trigger: 'blur' },
        // a5: { required: true, message: "合同编号", trigger: "blur" },
        contractTypeId: { required: true, message: '请选择分包方式', trigger: 'change' },
        textTypeId: { required: true, message: '请选择采用文本', trigger: 'blur' },
        contentSurvey: { required: true, message: '请填写分包工程/采购、租赁范围内容概况', trigger: 'blur' },
        actualSituation: { required: true, message: '请填写分供方合同谈判修改及落实情况', trigger: 'blur' },
        processTrend: { required: true, message: '请选择流程走向', trigger: 'change' },
        bcBmywjl: { required: true, message: '请选择分公司商务业务经理/业务主办', trigger: 'change' },
        coBmywzb: { required: true, message: '请选择公司商务业务经理/业务主办', trigger: 'change' },
        coLcmywzb: { required: true, message: '请选择合约法务部业务经理/业务主办', trigger: 'change' },

        a13: { required: true, message: '请选择工程部', trigger: 'change' },
        a14: { required: true, message: '请选择技术部', trigger: 'change' },
        a15: { required: true, message: '请选择财务资金部', trigger: 'change' },
        a16: { required: true, message: '请选择安全环境部', trigger: 'change' },
        a17: { required: true, message: '请选择物资管理部', trigger: 'change' }
      },
       subcontractorData:[],  //分包商数据
       pageNo: 1,
       pageSize: 100,
       totalPage: 0,
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  mounted: async function() {
    this.saveLoading = true
    this.saveLoading = false
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      await this.getBaseInfo()
    }
     //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('legal_review_yunzhu_new')
  },
  methods: {
    selectOrg(val) {
      if(val.length>1) {
        this.form.branchComName = val[val.length - 2].orgName
        !this.$route.query.id && this.$set(this.form, 'subcontractorScc', "")
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
        this.form.projectName = val[val.length - 1].projectName
      }
    },
    async getSubContractorAllFn(e){
         let req = {
           pageNo:this.pageNo,
           pageSize:this.pageSize,
           query:{
             name:e,
             branchComId:this.form?.branchComId
           }
         }
         let {data} = await subcontract.getSubContractorAll(req);
         if(data.length){
            data.map((item)=>{
              item.id=item.id?item.id:item.name
            })
         }
         if(e){
           this.subcontractorData = data;
         }else{
           this.subcontractorData = [... this.subcontractorData,...data]
         }
    },
    disabledDate(current) {
      if (this.form.startDate) {
        let startDate
        if (typeof this.form.startDate === 'string') {
          startDate = moment(this.form.startDate)
        } else {
          startDate = this.form.startDate
        }
        return current && current < moment(this.form.startDate)
      }
      return true
    },
    showProcessTrend() {
      if (this.form.id) {
        let processTrend = Number(this.form.processTrend)
        if (processTrend === 3 || processTrend === '3') {
          this.titleName = this.$route.meta.title = '补充协议'
        } else {
          this.titleName = this.$route.meta.title = '分包合同'
        }
        return processTrend !== 3
      } else {
        if (this.isContract) {
          this.titleName = this.$route.meta.title = '分包合同'
        } else {
          this.titleName = this.$route.meta.title = '补充协议'
        }
        return this.isContract
      }
    },
    async getBaseInfo() {
      this.saveLoading = true
      let res = await subcontract.findById({}, { id: this.form.id })
      if (res.code === this.SUCCESS_CODE) {
        res.data.signUsers.map(v => {
          if (v.type === '1') this.form.a13 = v
          if (v.type === '2') this.form.a14 = v
          if (v.type === '3') this.form.a15 = v
          if (v.type === '4') this.form.a16 = v
          if (v.type === '5') this.form.a17 = v
        })
        this.form = this.$assign(this.form, res.data)
        if (!this.form.file) this.form.file = []
        this.form.createTime2 = res.data.createTime

      }
      this.saveLoading = false
    },
    async submit() {
      // if (!await this.save('DRAFT', true)) {
      //   return
      // }
      if (await this.save('SUBMITTED', true)) {
      }
    },
    async save(auditStatus, isSubmit = false) {
      this.setProcessConfig = null;
      // return this.$console(this.form)
      return new Promise(async resolve => {
        let isPass = true
        if (isSubmit) {
          // if (!this.form.file.length) return this.$noticeWarning('请上传附件')
          this.$refs.form.validate(valid => {
            isPass = valid
            if(!valid) {
                this.$message.warning("请填写完所有必填项信息")
            }
          })
        } else {
          isPass = true
        }
        if (isPass) {
          let res
          let temp = this.$clone(this.form)
          temp.editPostCode = this.$currentPost().postCode
          temp.submitPostName = this.$currentPost().postCode
          temp.fromStatus = 1
          // temp.auditStatus = 'REJECTED'
          if (temp.auditStatus !== 'REJECTED') {
            temp.auditStatus = auditStatus
          }
          if (auditStatus === 'SUBMITTED') {
            temp.auditStatus = auditStatus
          }
          if (!isSubmit) {
            this.saveLoading = true
          } else {
            this.submitLoading = true
          }

          temp.signUsers = []
          if (this.form.a13?.label) temp.signUsers.push({ ...this.form.a13, type: 1 })
          if (this.form.a14?.label) temp.signUsers.push({ ...this.form.a14, type: 2 })
          if (this.form.a15?.label) temp.signUsers.push({ ...this.form.a15, type: 3 })
          if (this.form.a16?.label) temp.signUsers.push({ ...this.form.a16, type: 4 })
          if (this.form.a17?.label) temp.signUsers.push({ ...this.form.a17, type: 5 })

          this.submitApprovalConfirm(auditStatus === 'DRAFT'?6:this.processConfig, async (flag)=>{
            if(!flag) {
              this.saveLoading = false
              this.submitLoading = false
              return
            }
          if (temp.id) {
            res = await subcontract.update(temp)
          } else {
            res = await subcontract.add(temp)
          }
          if (res.code === 200) {
            this.form.id = res.data.id
            if (auditStatus === 'DRAFT') {
              if (!isSubmit) {
                this.$message.success('保存成功')
              }
              this.form.id = res.data.id
              await this.getBaseInfo()
            } else {
              this.$message.success('提交成功')
              //提交时，返回id
              this.businessId = res.data.id;
              this.setProcessConfig = this.processConfig;
            }
            resolve(true)
          }
          this.saveLoading = false
          this.submitLoading = false
          })
        }
      })
    }
  }
}
</script>
